﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MSI = Microsoft.Deployment.WindowsInstaller;
using IO = System.IO;
using SLP;
using System.Collections.ObjectModel;

namespace MsiCustomize
{
    /// <summary>
    /// Interaction logic for TableSchema.xaml
    /// would like to turn this into a direct MSI table Editor
    /// </summary>
    public partial class TableSchema : UserControl
    {
        private MstProject MSICP { get { try { return (MstProject)this.DataContext; } catch { return null; } } }
        private ObservableCollection<MsiTableSchemaItem> MsiTables;

        public TableSchema()
        {
            InitializeComponent();
            this.DataContextChanged += MsiProperties_DataContextChanged;
        }

        private void MsiProperties_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (MSICP != null)
                MSICP.PropertyChanged += MSICP_PropertyChanged;
        }

        private void MSICP_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            try
            {
                MSI.Database msi = new MSI.Database(IO.Path.Combine(MSICP.MsiFolder, MSICP.MsiFileName), MSI.DatabaseOpenMode.ReadOnly);
                MsiTables = new ObservableCollection<MsiTableSchemaItem>();
                foreach(MSI.TableInfo TableInfo in msi.Tables)
                {
                    string ColumnList = "";
                    foreach (MSI.ColumnInfo ColumnInfo in TableInfo.Columns)
                        ColumnList += ColumnInfo.Name + (ColumnInfo.IsRequired ? "*" : "") + "\v";
                    MsiTables.Add(new MsiTableSchemaItem() { TableName = TableInfo.Name, TableColumns = ColumnList.Trim().Replace("\v", " | ") });
                }
                DataView.ItemsSource = MsiTables;
            }
            catch { }
        }

    }
}
